package cn.qyd.atomic;

import sun.misc.Unsafe;
import sun.rmi.runtime.RuntimeUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;

/**
 * @author 邱运铎
 * @date 2024-03-25 10:38
 */
public class UnsafeClassLoad {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Unsafe unsafe = UnsafeDemo01.getUnsafe();
        //这里需要注意java版本不一致，在最后通过字节加载类时候会报版本异常，我这边就是使用jdk17去实例化jdk8编译的class文件导致最后报错
        File file = new File("src/cn/qyd/common/User.class");
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            byte[] content = new byte[(int) file.length()];
            fileInputStream.read(content);
            Class<?> aClass = unsafe.defineClass(null, content, 0, content.length, null, null);
            Object o = aClass.newInstance();
            //反射的时候调用带参数的方法，需要传入方法名称和参数类型
            aClass.getMethod("setAge",int.class).invoke(o, 18);
            Object age = aClass.getDeclaredMethod("getAge").invoke(o, null);
            System.out.println(age);
        } catch ( IOException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

    }
}
